package com.duowei.diandan.gson;

import android.util.Log;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

import org.joda.time.LocalDateTime;
import org.joda.time.format.DateTimeFormat;

import java.lang.reflect.Type;

public class LocalDateTimeDeserializer implements JsonDeserializer<LocalDateTime> {
    private static final String TAG = "LocalDateTimeDeser..";

    @Override
    public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        try {
            String s = json.getAsJsonPrimitive().getAsString();

            if (s.contains("T")) {
                return DateTimeFormat.forPattern("yyyyMMdd'T'HH:mm:ss").parseLocalDateTime(s);

            } else {
                return DateTimeFormat.forPattern("yyyyMMdd HH:mm:ss").parseLocalDateTime(s);
            }

        } catch (UnsupportedOperationException | IllegalArgumentException e) {
            Log.e(TAG, "deserialize: ", e);

            return null;
        }
    }
}
